<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="40%">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="80px"
      class="demo-ruleForm"
      :size="formSize"
      @close="handleClose"
    >
      <el-form-item label="新密码" prop="password">
        <el-input v-model="ruleForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="password_again">
        <el-input v-model="ruleForm.password_again" type="password"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-popconfirm
          title="是否确定修改？"
          width="220"
          @confirm="submitForm(ruleFormRef)"
        >
          <template #reference>
            <el-button type="primary">确定</el-button>
          </template>
        </el-popconfirm>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { editPassword } from '@/api/admin'
import { ref, reactive } from 'vue'
import { ElForm, ElMessageBox, ElNotification } from 'element-plus'
const dialogVisible = ref(false)
import { useUserStore } from '@/store/modules/user'
import { useRouter } from 'vue-router'
const UserStore = useUserStore()

const hide = () => {
  dialogVisible.value = false
}
type FormInstance = InstanceType<typeof ElForm>

const formSize = ref('')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id: '',
  password: '',
  password_again: '',
})
const show = (item = {}) => {
  dialogVisible.value = true
  if(item.id){
    ruleForm['id'] = item.id;
  }
}
const rules = reactive({
  password: [{ required: true, message: '请输入新的密码', trigger: 'blur' }],
  password_again: [{ required: true, message: '请再次输入密码', trigger: 'blur' }],
})
const router = useRouter()
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      editPassword(ruleForm).then(async (res) => {
        if (res.code == 200) {
          ElNotification({
              title: '修改成功',
              message: res.msg,
              type: 'success',
            })
            dialogVisible.value = false
          // await UserStore.logout()
          // await router.push({ path: '/login' })
        }
      })
    }
  })
}

const handleClose = () => {
  ruleForm.password = ''
  ruleForm.configPassword = ''
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

defineExpose({
  show,
})
</script>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
